<template>
  <div class="add-property-user">
    <!-- 页面头部 -->
    <el-card class="header-card" shadow="never">
      <div class="header-content">
        <div class="page-title">
          <h2>新增物业用户</h2>
          <p class="page-desc">为物业公司添加新用户账号</p>
        </div>
        <div class="header-actions">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 表单区域 -->
    <el-card class="form-card" shadow="never">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <!-- 用户类型选择 -->
        <el-form-item label="用户类型" prop="userType" required>
          <el-select
            v-model="formData.userType"
            placeholder="请选择用户类型"
            style="width: 100%"
            @change="handleUserTypeChange"
          >
            <el-option label="社区管理员" value="COMMUNITY_ADMIN" />
            <el-option label="物业人员" value="PROPERTY_STAFF" />
            <el-option label="安保人员" value="SECURITY_STAFF" />
            <el-option label="维修人员" value="REPAIR_STAFF" />
            <el-option label="居民" value="RESIDENT" />
            <el-option label="物业管理员" value="PROPERTY_ADMIN" />
            <el-option label="楼栋管理员" value="BUILDING_ADMIN" />
            <el-option label="单元管理员" value="UNIT_ADMIN" />
            <el-option label="房户管理员" value="HOUSEHOLD_ADMIN" />
            <el-option label="普通用户" value="NORMAL_USER" />
          </el-select>
        </el-form-item>

        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username" required>
              <el-input
                v-model="formData.username"
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName" required>
              <el-input
                v-model="formData.realName"
                placeholder="请输入真实姓名"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone" required>
              <el-input
                v-model="formData.phone"
                placeholder="请输入手机号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="formData.email"
                placeholder="请输入邮箱"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 物业公司关联信息 -->
        <el-divider content-position="left">物业公司关联信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input
                v-model="formData.position"
                placeholder="请输入职位"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input
                v-model="formData.department"
                placeholder="请输入部门"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工编号" prop="employeeNo">
              <el-input
                v-model="formData.employeeNo"
                placeholder="请输入员工编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="joinDate">
              <el-date-picker
                v-model="formData.joinDate"
                type="date"
                placeholder="请选择入职日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注信息 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <!-- 表单操作 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            <el-icon><Check /></el-icon>
            提交
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button @click="handleBack">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
/**
 * 新增物业用户页面
 * @author Wu.Liang
 * @date 2025-01-30
 */

import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back, Check, Refresh, Close } from '@element-plus/icons-vue'
import propertyCompanyApi from '@/api/property/propertyCompany'
import { showSuccess, showError, showWarning } from '@/utils/message'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const formRef = ref()
const submitting = ref(false)
const propertyCompanyId = ref<number>(0)
const propertyCompanyInfo = ref<any>({})

// 表单数据
const formData = reactive({
  userType: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  position: '',
  department: '',
  employeeNo: '',
  joinDate: '',
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 生命周期
onMounted(() => {
  const id = route.params.id
  if (id) {
    propertyCompanyId.value = Number(id)
    getPropertyCompanyInfo()
  } else {
    showError('物业公司ID不能为空')
    router.back()
  }
})

// 获取物业公司信息
const getPropertyCompanyInfo = async () => {
  try {
    const response = await propertyCompanyApi.getPropertyCompanyDetail(propertyCompanyId.value)
    if (response.code === 200) {
      propertyCompanyInfo.value = response.data
    } else {
      showError(response.message || '获取物业公司信息失败')
    }
  } catch (error) {
    console.error('获取物业公司信息失败:', error)
    showError('获取物业公司信息失败')
  }
}

// 用户类型变化处理
const handleUserTypeChange = (value: string) => {
  console.log('用户类型变化:', value)
  // 可以根据用户类型设置默认值
  switch (value) {
    case 'COMMUNITY_ADMIN':
      formData.position = '社区管理员'
      formData.department = '社区管理部'
      break
    case 'PROPERTY_STAFF':
      formData.position = '物业人员'
      formData.department = '物业服务部'
      break
    case 'SECURITY_STAFF':
      formData.position = '安保人员'
      formData.department = '安保部'
      break
    case 'REPAIR_STAFF':
      formData.position = '维修人员'
      formData.department = '维修部'
      break
    case 'PROPERTY_ADMIN':
      formData.position = '物业管理员'
      formData.department = '物业管理部'
      break
    case 'BUILDING_ADMIN':
      formData.position = '楼栋管理员'
      formData.department = '楼栋管理部'
      break
    case 'UNIT_ADMIN':
      formData.position = '单元管理员'
      formData.department = '单元管理部'
      break
    case 'HOUSEHOLD_ADMIN':
      formData.position = '房户管理员'
      formData.department = '房户管理部'
      break
    default:
      formData.position = ''
      formData.department = ''
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    // 确认提交
    await ElMessageBox.confirm(
      `确定要为物业公司"${propertyCompanyInfo.value.companyName}"新增用户"${formData.username}"吗？`,
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    submitting.value = true
    
    // 构建提交数据
    const submitData = {
      ...formData,
      propertyCompanyId: propertyCompanyId.value,
      status: 1 // 默认启用
    }
    
    // 调用API
    const response = await propertyCompanyApi.addPropertyUser(submitData)
    
    if (response.code === 200) {
      showSuccess('新增用户成功')
      router.push(`/property/company/detail/${propertyCompanyId.value}`)
    } else {
      showError(response.message || '新增用户失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('新增用户失败:', error)
      showError('新增用户失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    userType: '',
    username: '',
    realName: '',
    phone: '',
    email: '',
    position: '',
    department: '',
    employeeNo: '',
    joinDate: '',
    remark: ''
  })
}

// 返回
const handleBack = () => {
  // 返回到物业公司列表页面
  router.push('/property/company')
}
</script>

<style lang="scss" scoped>
.add-property-user {
  padding: 20px;
  
  .header-card {
    margin-bottom: 20px;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .page-title {
        h2 {
          margin: 0 0 8px 0;
          color: #303133;
        }
        
        .page-desc {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .form-card {
    .el-divider {
      margin: 24px 0 16px 0;
      
      :deep(.el-divider__text) {
        font-weight: 600;
        color: #303133;
      }
    }
    
    .el-form {
      max-width: 800px;
    }
  }
}
</style> 